import { DB } from '../../db'
import Md5 from '../../utils/md5'
import Moment from 'moment'
export default defineEventHandler(async (event) => {
  let {
    phone,
    password
  } = await readBody(event)
  const user = await DB.user.findOne({
    where: {
      phone,
      password: Md5(password)
    }
  })
  if (user) {
    // 检测用户是否被冻结
    const status = user.get('status')
    if (status === 0) {
      return {
        code: 201,
        msg: '该用户被冻结，请联系管理员'
      }
    }
    let lastLoginAt = await user.get('updatedAt')
    // 更新登录时间
    user.updatedAt = Moment().format('YYYY-MM-DD HH:mm:ss')
    await user.save()
    const data = {
      user: {
        userId: user.id,
        name: user.name,
        phone: user.phone,
        avatar: user.avatar,
        brief: user.brief,
        lastLoginAt
      },
      token: "token"
    }
    return {
      code: 200,
      msg: '登录成功',
      data
    }
  } else {
    return {
      code: 202,
      msg: '账号或密码错误'
    }
  }
})
